<template>
  <div class="app-container">
    <el-dialog
      :title="$t('common.select', [$t('customer.exportDataMethod')])"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form ref="form" label-width="100px">
        <el-form-item :label="$t('customer.exportMethod')">
          <el-radio-group v-model="exMode">
            <el-radio :label="1">{{ $t('common.exportChecked') }}</el-radio>
            <el-radio :label="2">{{ $t('common.exportByCondition') }}</el-radio>
            <!--            <el-radio :label="3">全部导出</el-radio>-->
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportData()">{{
          $t('common.submit')
        }}</el-button>
        <el-button @click="dialogVisible = false">{{
          $t('common.cancel')
        }}</el-button>
      </span>
    </el-dialog>
    <div ref="filter" class="filter-container" style="margin-bottom: unset">
      <el-input
        v-model="listQuery.name"
        size="small"
        :placeholder="$t('common.enter', [$t('common.title')])"
        style="width: 200px; margin-left: 5px"
        class="filter-item filter-left"
        clearable
      />
      <el-select
        v-model="listQuery.type"
        class="filter-left"
        :placeholder="$t('common.select', [$t('common.type')])"
        clearable
        filterable
        size="small"
      >
        <el-option
          v-for="item in typeOption"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <date-selector v-model="listQuery.updatedAt" style="width: 250px" />
      <el-button
        size="small"
        class="filter-item filter-left"
        icon="el-icon-search"
        type="primary"
        style="margin-left: 5px"
        plain
        @click="search()"
      />
      <!--        搜索-->
      <!--      </el-button>-->
    </div>
    <div ref="filter" class="filter-container">
      <el-button
        size="small"
        class="filter-item left"
        type="primary"
        style="margin-left: 5px"
        icon="el-icon-plus"
        @click="addRow()"
        v-if="isMy"
      >
        {{ $t('common.create') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px"
        icon="el-icon-s-grid"
        @click="setCustomerGroupCollect"
        v-if="isMy || isIntention"
      >
        {{ $t('customer.setGroup') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="danger"
        style="margin-left: 5px"
        icon="el-icon-price-tag"
        @click="setCustomerLabelCollect"
        v-if="isMy || isIntention"
        >{{ $t('customer.setupTag') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="info"
        style="margin-left: 5px"
        icon="el-icon-paperclip"
        @click="setCustomerSourceCollect"
        v-if="isMy || isIntention"
      >
        {{ $t('customer.setupSource') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px"
        icon="el-icon-star-on"
        @click="setCustomerIntentionCollect"
        v-if="isMy || isIntention"
      >
        {{ $t('customer.batchUpdateIntentState') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="primary"
        style="margin-left: 5px"
        icon="el-icon-star-on"
        @click="setCustomerEmailCollect"
        v-if="isMy || isIntention"
      >
        {{ $t('customer.newMarketingTask') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="danger"
        style="margin-left: 5px"
        icon="el-icon-delete"
        @click="batchDeleteBlock"
        v-if="isMy || isIntention"
      >
        {{ $t('customer.deleteData') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px"
        type="warning"
        icon="el-icon-upload2"
        @click="openExportCustomer()"
        v-if="(isMy || isIntention) && $common.IsInExe()"
      >
        {{ $t('common.export') }}
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px"
        type="success"
        icon="el-icon-collection"
        @click="downloadExportTemplate()"
        v-if="(isMy || isIntention) && $common.IsInExe()"
      >
        {{ $t('customer.downloadImportTemplate') }}
      </el-button>
      <!--      <el-button-->
      <!--        size="small"-->
      <!--        class="filter-item left"-->
      <!--        style="margin-left: 5px;"-->
      <!--        icon="el-icon-s-unfold"-->
      <!--        @click="setCustomerIsPrivateCollect(0)"-->
      <!--        v-if="isMy || isIntention"-->
      <!--      >-->
      <!--        批量移入公海-->
      <!--      </el-button>-->
      <!--      <el-button-->
      <!--        size="small"-->
      <!--        class="filter-item left"-->
      <!--        style="margin-left: 5px;"-->
      <!--        icon="el-icon-s-fold"-->
      <!--        @click="setCustomerIsPrivateCollect(1)"-->
      <!--        v-if="isWater"-->
      <!--      >-->
      <!--        批量认领客户-->
      <!--      </el-button>-->
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px"
        type="warning"
        icon="el-icon-upload2"
        @click="importCustomer()"
        v-if="isMy && $common.IsInExe()"
      >
        {{ $t('common.import') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      size="medium"
      :height="tableHeight"
      :header-cell-style="{ background: '#F2F6FC' }"
      @selection-change="handleSelection"
      class="customer"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column
        align="center"
        width="100"
        :label="$t('common.id')"
        type="index"
      />
      <el-table-column
        align="center"
        :label="$t('common.type')"
        width="120"
        prop="type"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <template v-if="row.from == 0">{{
            $t('customer.externalImport')
          }}</template>
          <template v-else-if="row.from == 1">{{
            $t('route.dataSearch')
          }}</template>
          <template v-else>{{ $t('customer.dataMarketing') }}</template>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.grouping')"
        width="150"
        prop="diyGroupId"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          {{ row.diyGroup ? row.diyGroup.name : $t('customer.notGrouping') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.source')"
        width="150"
        prop="sourceId"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          {{ row.source ? row.source.name : $t('customer.empty') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.tag')"
        width="180"
        type="index"
      >
        <template slot-scope="{ row }">
          <template v-if="row.labels">
            <template v-for="(v, k) in row.labels" style="margin-bottom: 2px">
              <el-tag
                :style="{
                  'background-color': v.color,
                  'border-color': v.color,
                }"
                size="mini"
                effect="dark"
              >
                {{ v.name }}
              </el-tag>
            </template>
          </template>
          <template v-else>{{ $t('customer.empty') }}</template>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('common.title')" prop="name" />
      <el-table-column
        align="center"
        :label="$t('common.domain')"
        min-width="75"
      >
        <template slot-scope="{ row }">
          <template v-if="row.url && row.domain">
            <el-link target="_blank" :href="row.url">{{ row.domain }}</el-link>
          </template>
          <template v-else> {{ $t('customer.empty') }} </template>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('common.description')">
        <template slot-scope="{ row }">
          {{ row.desc ? row.desc : $t('customer.empty') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('customer.belongTo')"
        v-if="currentUserInfo.userType == 3"
      >
        <template slot-scope="{ row }">
          {{ row.user ? row.user.trueName : $t('customer.empty') }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('common.createTime')"
        prop="belongAt"
        show-overflow-tooltip
      >
        <el-table-column
          align="center"
          :label="$t('common.latestOperationTime')"
          prop="followMessage"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            {{ row.createdAt }}
            <el-divider></el-divider>
            {{ row.updatedAt }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" width="250" :label="$t('common.actions')">
        <template slot-scope="{ row }">
          <template
            v-if="
              currentUserInfo.userType == 3 ||
              row.userId == currentUserInfo.userId
            "
          >
            <el-button-group>
              <el-button
                type="success"
                plain
                size="mini"
                @click="customerInfo(row.id, row.from)"
              >
                {{ $t('customer.viewDetail') }}
              </el-button>
              <el-button
                type="primary"
                plain
                size="mini"
                @click="editRow(row.id)"
              >
                {{ $t('common.edit') }}
              </el-button>
              <el-button
                type="danger"
                plain
                size="mini"
                @click="deleteRow(row.id)"
              >
                {{ $t('common.delete') }}
              </el-button>
            </el-button-group>
          </template>
          <template v-else>
            <el-button
              type="success"
              plain
              size="mini"
              @click="customerInfo(row.id, row.from)"
            >
              {{ $t('customer.viewDetail') }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />
    <block-drawer
      :id="blockId"
      :source="blockFrom"
      :action="listQuery.action"
      :show.sync="showCustomersState"
      @closeAction="refresh"
    />
    <group
      :id="collectId"
      :show.sync="showGroupState"
      :source="source"
      @closeAction="refresh"
    />
    <intention
      :id="collectId"
      :show.sync="showIntentionState"
      :source="source"
      @closeAction="refresh"
    />
    <label-com
      :id="collectId"
      :show.sync="showLabelState"
      :source="source"
      @closeAction="refresh"
    />
    <source-com
      :id="collectId"
      :show.sync="showSourceState"
      :source="source"
      @closeAction="refresh"
    />
    <email-add
      :emailsTemp="emailData"
      :show.sync="showBaseFormState"
      @closeAction="refresh"
    />
    <edit :id="id" :show.sync="showState" @closeAction="refresh" />
  </div>
</template>

<script>
import {
  deleteBlock,
  getCustomers,
  getExportCustomer,
  getList,
  SetIsPrivate,
} from '@/api/customer/block'
import { UserModule } from '@/store/modules/user'
import Pagination from '@/components/Pagination/index'
import BlockDrawer from '@/views/customer/index/blockDrawer'
import Group from '@/views/customer/common/group'
import LabelCom from '@/views/customer/common/label'
import Intention from '@/views/customer/common/intention'
import SourceCom from '@/views/customer/common/source'
import EmailAdd from '@/views/customer/index/emailAdd'
import Edit from '@/views/customer/block/edit'
import { deleteGroup } from '@/api/customer/group'
import DateSelector from '@/components/Public/dateSelector.vue'
import request from '@/utils/request'

export default {
  name: 'Block',
  components: {
    Pagination,
    Group,
    LabelCom,
    Intention,
    SourceCom,
    BlockDrawer,
    EmailAdd,
    Edit,
    DateSelector,
  },
  props: {
    action: {
      type: String,
    },
    tabIndex: {
      type: Number,
    },
  },
  inject: ['showProgressDialog'],
  data() {
    return {
      dialogVisible: false,
      exMode: 1,
      currentUserInfo: UserModule,
      emailData: [],
      source: 'block',
      isMy: false,
      isIntention: false,
      isWater: false,
      collectId: '',
      showCustomersState: false,
      showGroupState: false,
      showIntentionState: false,
      showLabelState: false,
      showSourceState: false,
      showBaseFormState: false,
      showState: false,
      id: '',
      clientHeight: document.documentElement.clientHeight,
      clientWidth: document.documentElement.clientWidth,
      listLoading: false,
      tableHeight: 'calc(100vh - 182px)',
      list: [],
      selection: [],
      total: 0,
      listQuery: {
        limit: 20,
        page: 1,
        action: 1,
        type: '',
        name: '',
        updatedAt: [],
      },
      typeOption: [
        { label: this.$t('route.dataSearch'), value: 1 },
        { label: this.$t('customer.dataMarketing'), value: 2 },
        { label: this.$t('customer.externalImport'), value: 0 },
      ],
      blockId: 0,
      blockFrom: 0,
    }
  },
  created() {
    this.checkTab()
  },
  mounted() {
    this.fetchData()
    window.onresize = () => {
      this.clientHeight = document.documentElement.clientHeight
      this.clientWidth = document.documentElement.clientWidth
    }
  },
  methods: {
    checkTab() {
      // 初始化
      this.isMy = false
      this.isIntention = false
      this.isWater = false
      if (this.action === 'my') {
        this.isMy = true
        this.listQuery.action = 1
      } // 我的客户
      if (this.action === 'intention') {
        this.isIntention = true
        this.listQuery.action = 2
      } // 意向客户
      if (this.action === 'water') {
        this.isWater = true
        this.listQuery.action = 3
      } //
    },
    async fetchData() {
      this.listLoading = true
      const listQuery = { ...this.listQuery }

      if (!listQuery.type) {
        delete listQuery.type
      }

      if (listQuery.updatedAt != null && listQuery.updatedAt.length != 0) {
        listQuery.updatedAtStart = listQuery.updatedAt[0] + ' 00:00:00'
        listQuery.updatedAtEnd = listQuery.updatedAt[1] + ' 23:59:59'
        delete listQuery.updatedAt
      }

      const { data } = await getList(listQuery, listQuery.page, listQuery.limit)
      this.list = data.items
      this.total = data.total
      if (this.total) {
        this.setTableHeight(315)
      } else {
        this.setTableHeight(273)
      }
      setTimeout(() => {
        this.listLoading = false
      }, 0.5 * 1000)
    },
    setTableHeight(height) {
      this.tableHeight = 'calc(100vh - ' + height + 'px)'
    },
    customerInfo(id, from) {
      this.blockId = id
      this.blockFrom = from
      this.showCustomersState = true
    },
    refresh() {
      // 刷新重置条件
      this.listQuery = {
        limit: 20,
        page: 1,
        action: this.listQuery.action,
        type: '',
        name: '',
        updatedAt: [],
      }
      this.showCustomersState = false
      this.showGroupState = false
      this.showIntentionState = false
      this.showLabelState = false
      this.showSourceState = false
      this.showBaseFormState = false
      this.showState = false
      this.fetchData()
    },
    importCustomer() {
      const _this = this
      this.$common.ExeInvoke(function (f) {
        f.ImportClient()
      })
      this.importCallBack()
    },
    async exportData() {
      let ids = []
      // 勾选导出
      if (this.exMode == 1) {
        if (this.selection.length <= 0) {
          this.$message({
            type: 'info',
            message: this.$t('customer.checkDataNeedToBatchExport'),
          })
          return false
        }
        for (const i in this.selection) {
          ids.push(this.selection[i].id)
        }
      } else if (this.exMode == 2) {
        const listQuery = { ...this.listQuery }

        if (!listQuery.type) {
          delete listQuery.type
        }

        if (listQuery.updatedAt != null && listQuery.updatedAt.length != 0) {
          listQuery.updatedAtStart = listQuery.updatedAt[0] + ' 00:00:00'
          listQuery.updatedAtEnd = listQuery.updatedAt[1] + ' 23:59:59'
          delete listQuery.updatedAt
        }
        await request
          .post('/api/block/customerExportBlockIds', listQuery)
          .then((res) => {
            ids = res.data
          })

        if (ids.length === 0) {
          this.$message({
            type: 'info',
            message: this.$t('customer.dataNotFound'),
          })
          return false
        }
      }
      if (UserModule.settings?.validateEmailBeforeExport) {
        await this.batchVerifyBlockEmailsDialog(ids)
      }

      await getCustomers(ids).then((res) => {
        if (res.data.length) {
          const ids = []
          for (const i in res.data) {
            ids.push(res.data[i].id)
          }
          this.dialogVisible = false
          this.$common.ExeInvoke(function (f) {
            f.ExportClient(ids)
          })
        } else {
          this.dialogVisible = false
          this.$message({
            type: 'info',
            message: this.$t('customer.dataNotFound'),
          })
        }
      })
    },
    openExportCustomer() {
      this.dialogVisible = true
      this.exMode = 1
    },
    search() {
      this.fetchData()
    },
    setCustomerGroupCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('customer.checkDataNeedToSetGroup'),
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showGroupState = true
    },
    setCustomerLabelCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('customer.checkDataNeedToSetTag'),
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showLabelState = true
    },
    setCustomerSourceCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('customer.checkDataNeedToSetSource'),
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showSourceState = true
    },
    handleSelection(val) {
      this.selection = val
    },
    setCustomerIsPrivateCollect(val = 0) {
      if (this.selection.length <= 0) {
        let msg = ''
        if (val == 0) {
          msg = this.$t('customer.checkCustomerNeedToBatchMoveToPublic')
        } else {
          msg = this.$t('customer.checkCustomerNeedToBatchClaim')
        }
        this.$message({
          type: 'info',
          message: msg,
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = ''
      let title = ''
      if (val == 0) {
        title = this.$t('customer.moveTo')
        msg = this.$t('customer.confirmMoveInPublic')
      } else {
        title = this.$t('customer.claim')
        msg = this.$t('customer.confirmClaim')
      }

      this.$confirm(msg, this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      }).then(async () => {
        const data = { ids: this.collectId, value: val }

        if (typeof data.ids !== 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: this.$t('common.success'),
            message: `${title}${this.$t('common.success')}`,
            type: 'success',
            duration: 2000,
          })
          this.fetchData()
        })
      })
    },
    setCustomerIntentionCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('customer.checkNeedToBatchUpdateIntentState'),
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showIntentionState = true
    },
    batchDeleteBlock() {
      if (this.selection.length <= 0) {
        this.$message(this.$t('customer.checkDataNeedToBatchDelete'))
        return false
      }
      const uploadItems = [
        {
          name: this.$t('dataSearch.data'),
          num: this.selection.length,
          action: this.batchDeleteFunc,
          data: this.selection,
        },
      ]
      const uploadColumns = [
        { label: this.$t('common.title'), key: 'name', popover: true },
      ]
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, {
        title: this.$t('common.batchDeleteCantReverse'),
      })
    },
    async batchDeleteFunc({ item, message }) {
      await deleteBlock({ id: item.id, type: this.tabIndex })
        .then(() => {
          message.success(
            '[' + item.name + '] ' + this.$t('common.deleteSuccessfully')
          )
        })
        .catch((res) => {
          message.failed('[' + item.name + '] ' + res.message)
        })
    },
    async setCustomerEmailCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('customer.checkMarketingTaskNeedToBatchCreate'),
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      await getCustomers(ids).then((res) => {
        this.emailData = res.data
        if (this.emailData.length) {
          this.showBaseFormState = true
        } else {
          this.$message({
            type: 'info',
            message: this.$t('customer.emailNotFound'),
          })
        }
      })
    },
    addRow() {
      this.id = ''
      this.showState = true
    },
    editRow(id) {
      this.id = id
      this.showState = true
    },
    downloadExportTemplate() {
      window.open('/api/download/import')
    },
    deleteRow(id) {
      this.$confirm(this.$t('common.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      })
        .then(async () => {
          this.listLoading = true
          await deleteBlock({ id: id, type: this.tabIndex }).then((res) => {
            this.$notify({
              title: this.$t('common.success'),
              message: this.$t('common.deleteSuccessfully'),
              type: 'success',
              duration: 2000,
            })
            this.fetchData()
          })
        })
        .catch(() => {
          this.fetchData()
        })
    },
    batchVerifyBlockEmailsDialog(ids) {
      return new Promise((resolve, reject) => {
        if (ids.length === 0) {
          return resolve()
        }

        const singleValidationStepAction = ({ item, message, index }) => {
          request({
            method: 'post',
            url: `/api/block/verifyBlockEmails/${item.blockId}`,
            timeout: 0,
          }).then((res) => {
            message.success(
              `[块#${item.blockId}]第${index + 1}次验证邮箱成功`,
              uploadItems
            )
          })
        }

        const singleBlockAction = ({ item, message, index }) => {
          request
            .get(`/api/block/getValidationProgressCount/${item.id}`)
            .then((res) => {
              const count = res.data
              const data = []
              for (let i = 0; i < count; i++) {
                data.push({ blockId: item.id })
              }
              const uploadItems = [
                { name: '验证邮箱', action: singleValidationStepAction, data },
              ]
              message.subTask(`[块#${item.id}]开始验证邮箱`, uploadItems)
            })
        }
        const data = ids.map((id) => ({ id }))
        const uploadItems = [{ name: '块', action: singleBlockAction, data }]
        this.showProgressDialog(
          uploadItems,
          [],
          () => {
            resolve()
          },
          {
            autoClose: true,
            autoStart: true,
          }
        )
      })
    },
  },
}
</script>

<style scoped>
.customer /deep/ .el-divider--horizontal {
  margin: 5px 0 !important;
}
</style>
